package com.lottery.material.service.admin.circle.impl;

import com.lottery.material.config.upload.UploadFileConfig;
import com.lottery.material.dao.circle.CircleInfoMapper;
import com.lottery.material.dao.circle.CircleMemberInfoMapper;
import com.lottery.material.dao.conf.MenuLevelConfigMapper;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.enumeration.circle.CircleInfoEnum;
import com.lottery.material.enumeration.circle.CircleMemberInfoEnum;
import com.lottery.material.enumeration.common.CommonEnum;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojocustom.circle.CircleInfoCustom;
import com.lottery.material.service.admin.circle.CircleInfoService;
import com.lottery.material.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Description：圈子信息服务接口实现类
 * Created by 朱正磊 on 2019-04-13 15:33
 */
@Slf4j
@Service("adminCircleInfoService")
public class CircleInfoServiceImpl implements CircleInfoService {

    private final CircleInfoMapper circleInfoMapper;

    private final MenuLevelConfigMapper menuLevelConfigMapper;

    private final UploadFileConfig uploadFileConfig;

    private final CircleMemberInfoMapper circleMemberInfoMapper;

    @Autowired
    public CircleInfoServiceImpl(CircleInfoMapper circleInfoMapper,
                                 MenuLevelConfigMapper menuLevelConfigMapper,
                                 UploadFileConfig uploadFileConfig,
                                 CircleMemberInfoMapper circleMemberInfoMapper) {
        this.circleInfoMapper = circleInfoMapper;
        this.menuLevelConfigMapper = menuLevelConfigMapper;
        this.uploadFileConfig = uploadFileConfig;
        this.circleMemberInfoMapper = circleMemberInfoMapper;
    }

    /**
     * description：新增一条数据
     * user 朱正磊
     * time 2019-04-17 17:06
     * @param request 请求对象
     * @param circleInfo 对象
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer add(HttpServletRequest request, CircleInfo circleInfo) {

        //设置背景图片和圈子头像
        this.setPictureByOSS(request, circleInfo);

        circleInfo.setCreateTime(new Date());//创建时间
        circleInfo.setState((Integer) CommonEnum.STATE_OFF.getValue());//默认下架

        //设置发帖间隔（秒）
        this.setSendInterval(request, circleInfo);

        //插入一条圈子记录
        Integer flag = circleInfoMapper.insertSelective(circleInfo);
        if (Objects.equals(flag, 0)) {
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            CircleMemberInfo circleMemberInfo = new CircleMemberInfo();
            circleMemberInfo.setCreateTime(new Date());
            String userId = request.getParameter("userId");
            circleMemberInfo.setUserId(userId);
            circleMemberInfo.setCircleId(circleInfo.getId());
            circleMemberInfo.setRank((Integer) CircleMemberInfoEnum.RANK_MAIN.getValue());
            //插入一条圈子成员记录
            flag = circleMemberInfoMapper.insertSelective(circleMemberInfo);
        }
        return flag;
    }

    /**
     * description：根据主键物理删除
     * user 朱正磊
     * time 2019-04-20 15:13
     * @param id 主键
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer deleteById(Integer id) {
        return circleInfoMapper.deleteByPrimaryKey(id);
    }

    /**
     * description：根据主键查询唯一数据
     * user 朱正磊
     * time 2019-04-19 20:11
     * @param id 主键
     * @return 返回唯一数据
     */
    @Override
    public CircleInfo findById(Integer id) {
        return circleInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * description：根据主键修改一条数据
     * user 朱正磊
     * time 2019-04-17 17:09
     * @param request 请求对象
     * @param circleInfo 对象
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateById(HttpServletRequest request, CircleInfo circleInfo) {
        if (AssertUtil.isEmpty(request)) { //判断必须加
            return circleInfoMapper.updateByPrimaryKeySelective(circleInfo);
        } else {
            //设置背景图片和圈子头像
            this.setPictureByOSS(request, circleInfo);

            //设置发帖间隔（秒）
            this.setSendInterval(request, circleInfo);

            //判断是否修改了圈主
            List<CircleMemberInfo> circleMemberInfoList = circleMemberInfoMapper.findByCircleIdAndRank(circleInfo.getId(),
                    (Integer) CircleMemberInfoEnum.RANK_MAIN.getValue());
            CircleMemberInfo circleMemberInfo = circleMemberInfoList.get(0);
            Integer flag;
            if (!Objects.equals(circleMemberInfo.getUserId(), request.getParameter("userId"))) { //修改了圈主
                circleMemberInfo.setUserId(request.getParameter("userId"));
                flag = circleMemberInfoMapper.updateByPrimaryKeySelective(circleMemberInfo);
                if (Objects.equals(flag, 0)) {
                    throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
                }
            }
            return  circleInfoMapper.updateByPrimaryKeySelective(circleInfo);
        }
    }

    /**
     * description： 设置图片（使用OSS）
     * user 朱正磊
     * time 2019-04-23 09:43
     * @param request 请求对象
     * @param circleInfo 圈子对象
     */
    private void setPictureByOSS(HttpServletRequest request, CircleInfo circleInfo) {
        //采用OSS作为图片服务器
        String pictureAddressOne = OSSClientUtil.uploadFiles(uploadFileConfig,
                FileUploadUtil.getMultipartFiles(request, "pictureAddressOne"), uploadFileConfig.getCircleInfoModuleName());
        if (AssertUtil.isNotEmpty(pictureAddressOne)) {
            //设置背景图片
            circleInfo.setBackgroundImageUrl(pictureAddressOne);
        }

        //采用OSS作为图片服务器
        String pictureAddressTwo = OSSClientUtil.uploadFiles(uploadFileConfig,
                FileUploadUtil.getMultipartFiles(request, "pictureAddressTwo"), uploadFileConfig.getCircleInfoModuleName());
        if (AssertUtil.isNotEmpty(pictureAddressTwo)) {
            //设置圈子头像
            circleInfo.setCircleIcon(pictureAddressTwo);
        }
    }

    /**
     * description： 设置图片（使用nginx）
     * user 朱正磊
     * time 2019-04-23 09:43
     * @param request 请求对象
     * @param circleInfo 圈子对象
     */
    @SuppressWarnings("unused")
    private void setPictureByNginx(HttpServletRequest request, CircleInfo circleInfo) {
        //采用nginx作为图片服务器
        String pictureAddressOne = FileUploadUtil.getPictureUrl(request, uploadFileConfig.getProjectName(),
                uploadFileConfig.getCircleInfoModuleName(), "pictureAddressOne", FtpUtil.getFtpConfig(uploadFileConfig));
        if (AssertUtil.isNotEmpty(pictureAddressOne)) {
            //设置背景图片
            circleInfo.setBackgroundImageUrl(pictureAddressOne);
        }

        //采用nginx作为图片服务器
        String pictureAddressTwo = FileUploadUtil.getPictureUrl(request, uploadFileConfig.getProjectName(),
                uploadFileConfig.getCircleInfoModuleName(), "pictureAddressTwo", FtpUtil.getFtpConfig(uploadFileConfig));
        if (AssertUtil.isNotEmpty(pictureAddressTwo)) {
            //设置圈子头像
            circleInfo.setCircleIcon(pictureAddressTwo);
        }
    }

    /**
     * description：设置发帖间隔
     * user 朱正磊
     * time 2019-04-23 09:50
     * @param request 请求对象
     * @param circleInfo 圈子对象
     */
    private void setSendInterval(HttpServletRequest request, CircleInfo circleInfo) {
        //发帖间隔（秒）
        String hourStr = request.getParameter("hour");
        String minuteStr = request.getParameter("minute");

        Integer hourInt;
        Integer minuteInt;
        Integer sendInterval = 0;
        if (AssertUtil.isNotEmpty(hourStr) && AssertUtil.isNotEmpty(minuteStr)) {
            hourInt = Integer.valueOf(hourStr);
            minuteInt = Integer.valueOf(minuteStr);
            sendInterval = (hourInt * 60 + minuteInt) * 60;
        }
        if (AssertUtil.isNotEmpty(hourStr) && AssertUtil.isEmpty(minuteStr)) {
            hourInt = Integer.valueOf(hourStr);
            sendInterval = hourInt * 60 * 60;
        }
        if (AssertUtil.isEmpty(hourStr) && AssertUtil.isNotEmpty(minuteStr)) {
            minuteInt = Integer.valueOf(minuteStr);
            sendInterval = minuteInt * 60;
        }
        circleInfo.setSendInterval(sendInterval);
    }

    /**
     * description：查询扩展类分页列表
     * user 朱正磊
     * time 2019-04-17 17:01
     * @param page 分页对象
     * @return 返回扩展类分页列表数据
     */
    @Override
    public List<CircleInfoCustom> findCustomListPage(Page page) {
        List<CircleInfoCustom> list = circleInfoMapper.findCustomListPage(page);
        list.forEach(this::setCustom);
        return list;
    }

    /**
     * description：根据主键查询唯一扩展类数据
     * user 朱正磊
     * time 2019-04-17 17:03
     * @param id 主键
     * @return 返回唯一扩展类数据
     */
    @Override
    public CircleInfoCustom findCustomById(Integer id) {
        CircleInfoCustom custom = circleInfoMapper.findCustomById(id);
        this.setCustom(custom);
        return custom;
    }

    /**
     * description：设置扩展类的扩展属性
     * user 朱正磊
     * time 2019-04-17 17:48
     * @param custom 扩展类对象
     */
    private void setCustom(CircleInfoCustom custom) {
        //创建时间
        custom.setCreateTimeFormat(CalendarUtil.dateToString(custom.getCreateTime()));
        //是否标记为热门圈子（1：否；2：是）
        custom.setIsHotCircleDesc(EnumUtil.getDescriptionByCodeValue(CircleInfoEnum.IS_HOT_CIRCLE,
                custom.getIsHotCircle(), CircleInfoEnum.class));
        //是否进入精彩（1：否；2：是）
        custom.setIsWonderfulDesc(EnumUtil.getDescriptionByCodeValue(CircleInfoEnum.IS_WONDERFUL,
                custom.getIsWonderful(), CircleInfoEnum.class));
        //是否禁止评论（1：否；2：是）
        custom.setIsProhibitionCommentDesc(EnumUtil.getDescriptionByCodeValue(CircleInfoEnum.IS_PROHIBITION_COMMENT,
                custom.getIsProhibitionComment(), CircleInfoEnum.class));
        //是否禁止发贴（1：否；2：是）
        custom.setIsProhibitionPublishDesc(EnumUtil.getDescriptionByCodeValue(CircleInfoEnum.IS_PROHIBITION_PUBLISH,
                custom.getIsProhibitionPublish(), CircleInfoEnum.class));
        //状态 1：上架；2：下架
        custom.setStateDesc(EnumUtil.getDescriptionByCodeValue(CommonEnum.STATE,
                custom.getState(), CommonEnum.class));
        //所属二级类别
        String menuTwoLevelName = menuLevelConfigMapper.findMenuNameByMenuCode(custom.getSubTypeCode());
        if (AssertUtil.isNotEmpty(menuTwoLevelName)) {
            custom.setMenuTwoLevelName(menuTwoLevelName);
        }
        //所属一级类别
        String menuOneLevelName = menuLevelConfigMapper.findMenuNameByMenuCode(custom.getMainTypeCode());
        if (AssertUtil.isNotEmpty(menuOneLevelName)) {
            custom.setMenuOneLevelName(menuOneLevelName);
        }
    }

    /**
     * description：更新二级类别下的圈子的上下架状态（用来下架）
     * user 朱正磊
     * time 2019-04-23 18:03
     * @param subTypeCode 二级类别编号
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateBySubTypeCode(String subTypeCode) {
        // 查询二级类别下所有未下架的圈子
        List<CircleInfo> list = circleInfoMapper
                .findBySubTypeCodeAndState(subTypeCode, (Integer) CommonEnum.STATE_ON.getValue());
        Integer flag = 1;
        for (CircleInfo circleInfo : list) {
            circleInfo.setState((Integer) CommonEnum.STATE_OFF.getValue()); //进行下架
            flag = circleInfoMapper.updateByPrimaryKeySelective(circleInfo);
            if (Objects.equals(0, flag)) {
                break;
            }
        }
        return flag;
    }

    /**
     * description：批量上架
     * user 朱正磊
     * time 2019-04-24 16:37
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateBatchOn(String ids) {
        Map<String, Object> data = new HashMap<>();
        data.put("idList", ListUtil.getIdList(ids));
        data.put("state", CommonEnum.STATE_ON.getValue());
        return circleInfoMapper.updateBatchState(data);
    }

    /**
     * description：批量下架
     * user 朱正磊
     * time 2019-04-24 16:37
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateBatchOff(String ids) {
        Map<String, Object> data = new HashMap<>();
        data.put("idList", ListUtil.getIdList(ids));
        data.put("state", CommonEnum.STATE_OFF.getValue());
        return circleInfoMapper.updateBatchState(data);
    }

    /**
     * description：批量选入精彩页面
     * user 朱正磊
     * time 2019-04-24 16:37
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateBatchIsWonderful(String ids) {
        Map<String, Object> data = new HashMap<>();
        data.put("idList", ListUtil.getIdList(ids));
        data.put("isWonderful", CircleInfoEnum.IS_WONDERFUL_TRUE.getValue());
        return circleInfoMapper.updateBatchIsWonderful(data);
    }

    /**
     * description：批量撤出精彩页面
     * user 朱正磊
     * time 2019-04-24 16:37
     * @param ids 主键集合(多个id以,进行拼接)
     * @return 返回持久化操作数据库状态值
     */
    @Override
    public Integer updateBatchIsNotWonderful(String ids) {
        Map<String, Object> data = new HashMap<>();
        data.put("idList", ListUtil.getIdList(ids));
        data.put("isWonderful", CircleInfoEnum.IS_WONDERFUL_FALSE.getValue());
        return circleInfoMapper.updateBatchIsWonderful(data);
    }

    /**
     * description：根据圈子名称查询圈子列表（可以不存在，如果存在只允许存在一条数据）
     * user 朱正磊
     * time 2019-04-25 15:56
     * @param circleName 圈子名称
     * @return 返回圈子列表
     */
    @Override
    public List<CircleInfo> findByCircleName(String circleName) {
        return circleInfoMapper.findByCircleName(circleName);
    }

    /**
     * description：根据上下架状态查询列表数据
     * user 朱正磊
     * time 2019-05-28 14:13
     * @param state 上下架状态
     * @return 返回列表数据
     */
    @Override
    public List<CircleInfo> findListByState(Integer state) {
        return circleInfoMapper.findListByState(state);
    }

}
